// pages/answer/answer.js
import request from '../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    groups: '', //用户组别
    countdown: 0,
    timer: '',
    questionList: [], //题库
    currentIndex: 0, //当前第n道题
    currentOptionNo: '', //当前页面选项
    scores: 0, //分数
    totalScore: 0, //试卷满分
    rightList: [], //回答正确的题
    answerList: [], //学生答案
    showAnimation: false, // 20控制动画显示
    animationClass: '', // 动画类名
    showImageAnimation: false, // 40新增的状态
    imageAnimationClass: '', // 新增的图片动画类
    showSixImageAnimation: false, //60
    showEigImageAnimation: false, //80
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      countdown: userInfo.examDuration,
      groups: userInfo.groups
    })

    //获取题库
    this.getQuestionList();

    this.startCountdown(); //开启定时器
  },

  //开启定时器
  startCountdown: function () {
    const that = this;
    that.data.timer = setTimeout(function () {
      if (that.data.countdown > 0) {
        that.setData({
          countdown: that.data.countdown - 1
        });
        that.startCountdown(); // 递归调用，实现倒计时
      } else {
        let params = wx.getStorageSync('userInfo') || {}
        params.studentAnswerList = that.data.answerList
        params.examTotalScore = that.data.totalScore
        //提交试卷
        request('/tiku/wechat/answer', 'post', params).then(res => {
          if (res.code == 200) {
            wx.redirectTo({
              url: '/pages/success/success'
            });
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false, // 如果不需要取消按钮可以设置为 false
            });
          }

        })

      }
    }, 1000); // 每秒更新一次
  },

  getQuestionList() {
    const params = {
      pageNo: 1,
      pageSize: 100,
      questionType: 1,
      groups: this.data.groups
    }
    request('/tiku/wechat/question/list', 'post', params).then(res => {
      this.setData({
        questionList: res.data.list
      })

      //计算试卷满分
      let maxScore = this.data.questionList.reduce((sum, question) => {
        return sum + question.questionScore; // 将 questionScore 累加到 sum 上
      }, 0); // 初始值是 0
      this.setData({
        totalScore: maxScore
      })

      //取出题目和分数
      const newList = this.data.questionList.map(item => ({
        questionId: item.questionId,
        questionScore: 0
      }))
      this.setData({
        answerList: newList
      })
    })
  },


  // answer(event) {
  //   const selectedOption = event.currentTarget.dataset.option.correctAnswer
  //   //选择的选项加入数组
  //   this.data.answerList[this.data.currentIndex].optionNo = event.currentTarget.dataset.option.optionNo

  //   //回答正确加入数组
  //   let array = this.data.rightList
  //   if (selectedOption) {
  //     //判断为1加分
  //     this.data.answerList[this.data.currentIndex].questionScore = this.data.questionList[this.data.currentIndex].questionScore

  //     array.push(this.data.currentIndex)
  //     this.setData({
  //       rightList: array
  //     });
  //   }

  //   this.setData({
  //     scores: this.data.scores + selectedOption,
  //     currentIndex: this.data.currentIndex + 1
  //   });
  // },
  //点击选项
  answer(event) {
    const selectedOption = event.currentTarget.dataset.option.correctAnswer;
    const selectedOptionNo = event.currentTarget.dataset.option.optionNo;

    // 获取当前 index 的副本
    const currentIndex = this.data.currentIndex;

    // 创建 answerList 的副本
    const updatedAnswerList = this.data.answerList.slice();

    // 选择的选项加入数组
    updatedAnswerList[currentIndex].optionNo = selectedOptionNo;

    // 创建 rightList 的副本
    const updatedRightList = this.data.rightList.slice();

    // 回答正确加入数组
    if (selectedOption) {
      // 判断为1加分
      updatedAnswerList[currentIndex].questionScore = this.data.questionList[currentIndex].questionScore;

      // 将当前索引加入 rightList
      updatedRightList.push(currentIndex);
    }

    // 使用 setData 更新状态
    this.setData({
      answerList: updatedAnswerList,
      rightList: updatedRightList,
      scores: this.data.scores + selectedOption,
    });

    //进入下一题
    // this.nextQuestion();

    //根据已答题数显示动画
    const filteredAnswers = this.data.answerList.filter(answer => answer.optionNo);
    if (filteredAnswers.length == 20) {
      this.setData({
        showAnimation: true,
        animationClass: 'fade-20' // 或者其他你定义的动画类
      });

      // 5秒后隐藏动画
      setTimeout(() => {
        this.setData({
          showAnimation: false,
          animationClass: '' // 重置动画类
        });
      }, 5000);
    }

    // 40题动画
    if (filteredAnswers.length === 40) {
      this.setData({
        showImageAnimation: true,
        imageAnimationClass: 'fade-40' // 使用你的图片动画类
      });

      // 5秒后隐藏图片动画
      setTimeout(() => {
        this.setData({
          showImageAnimation: false,
          imageAnimationClass: ''
        });
      }, 5000);
    }

    // 60题动画
    if (filteredAnswers.length === 60) {
      this.setData({
        showSixImageAnimation: true,
      });

      // 5秒后隐藏图片动画
      setTimeout(() => {
        this.setData({
          showSixImageAnimation: false,
        });
      }, 5000);
    }

    // 80题动画
    if (filteredAnswers.length === 80) {
      this.setData({
        showEigImageAnimation: true,
      });

      // 5秒后隐藏图片动画
      setTimeout(() => {
        this.setData({
          showEigImageAnimation: false,
        });
      }, 5000);
    }

  },

  //下一题
  nextQuestion() {
    if (this.data.currentIndex < this.data.questionList.length - 1) {
      this.setData({
        currentIndex: this.data.currentIndex + 1
      });
    }
  },

  //上一题
  previousQuestion() {
    if (this.data.currentIndex > 0) {
      const {
        rightList,
        currentIndex,
        scores
      } = this.data;

      if (rightList.includes(currentIndex - 1)) {
        // 使用 filter 方法移除元素
        const updatedList = rightList.filter(item => item !== currentIndex - 1);
        // 返回时扣一分
        this.setData({
          rightList: updatedList,
          scores: updatedList.length
        });
      }

      this.setData({
        currentIndex: this.data.currentIndex - 1
      });
    } else {
      wx.showToast({
        title: '已经是第一题了',
        icon: 'success'
      });
    }
  },

  //点击交卷
  submit() {
    let params = wx.getStorageSync('userInfo') || {}
    params.studentAnswerList = this.data.answerList
    params.examTotalScore = this.data.totalScore
    //提交试卷
    request('/tiku/wechat/answer', 'post', params).then(res => {
      console.log(res);
      wx.redirectTo({
        url: '/pages/success/success'
      });
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearTimeout(this.data.timer); // 清除定时器
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})